// 运动相关控制器
const axios = require("axios");
const Do = require("../../models/Do");
const WXBizDataCrypt = require("./WXBizDataCrypt");
const { getdate } = require("./utils");

// 微信小程序配置
const appid = "wxd7d797edc9bd4e32";
const secret = "1185a90fcb9f6979931e2ff1d0a076a5";

/**
 * 获取运动步数
 */
async function getRunData(req, res) {
  const { encryptedData, iv, code } = req.body;
  const { openid } = req.query;
  
  try {
    const wxResponse = await axios.get(
      `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`
    );
    
    const sessionKey = wxResponse.data.session_key;
    let pc = new WXBizDataCrypt(appid, sessionKey);

    let stepInfoList = pc
      .decryptData(encryptedData, iv)
      .stepInfoList.slice(-4);
    
    const model = stepInfoList.map((el) => {
      let date = getdate(el.timestamp);
      return {
        date,
        step: el.step,
      };
    });
    
    let doRecord = await Do.findOne({ openid });
    
    if (!doRecord) {
      // 如果用户没有运动记录，创建一个新的
      doRecord = new Do({
        openid,
        exercise: 5000,
        sport: [],
        score: {}
      });
    }
    
    // 获取用户设置的目标步数，如果没有则使用默认值 5000
    const targetSteps = doRecord.exercise || 5000;
    
    // 更新步数数据，保留目标步数
    doRecord.score = {
      first_target: targetSteps,
      second_target: targetSteps,
      third_target: targetSteps,
      fourth_target: targetSteps,
      first_step: model[0].step,
      second_step: model[1].step,
      third_step: model[2].step,
      fourth_step: model[3].step,
      first_date: model[0].date,
      second_date: model[1].date,
      third_date: model[2].date,
      fourth_date: model[3].date,
      // 保留之前的运动消耗数据
      calorie_burn: doRecord.score.calorie_burn || 0,
      fat_burn: doRecord.score.fat_burn || 0,
      carbohydrate_burn: doRecord.score.carbohydrate_burn || 0,
      protein_burn: doRecord.score.protein_burn || 0
    };
    
    const updatedRecord = await Do.findOneAndUpdate(
      { openid }, 
      doRecord, 
      { new: true, upsert: true }
    );
    
    res.send({
      success: true,
      message: '步数数据更新成功',
      data: updatedRecord
    });
  } catch (err) {
    console.error('获取运动数据错误:', err);
    res.status(400).send({
      success: false,
      message: err.message || '获取运动数据失败'
    });
  }
}

module.exports = {
  getRunData
};

